<template>
  <div ref="echartsBarPieTop" style="height: 300px" />
</template>

<script>
import * as echarts from 'echarts'
export default {
  name: 'EchartsPie',
  props: {
    dataList: {
      type: Array,
      default() {
        return []
      }
    },
    legend: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      myChart: null // 用来存放图形实例
    }
  },
  watch: {
    dataList(values) {
      if (values && values.length) {
        this.InitEcharts(values)
      }
    }
  },
  mounted() {
    this.InitEcharts(this.dataList)
  },
  beforeDestroy() {
    // 销毁监听事件
    window.removeEventListener('resize', this.resizeHandler)
    // 销毁 Echarts 实例
    this.myChart && this.myChart.dispose()
  },
  methods: {
    // 初始化echarts
    InitEcharts(values) {
      this.legend.length || this.legend.push('无')
      const color = ['#9fe6b8', '#ffdb5c', '#fb7293', '#5470c6', '#91cc75', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#80FFA5', '#00DDFF', '#37A2FF', '#FF0087', '#FFBF00']
      const newData = values.map(item => {
        const { contractPrice, qualificationLevel, countCounty, proportion } = item
        return { name: qualificationLevel, value: countCounty, proportion, contractPrice: this.divideMoney(contractPrice, 6, true) }
      })
      this.myChart = echarts.init(this.$refs['echartsBarPieTop'])
      const options = {
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            const res = `<p> ${params.name}项目数：${params.value}个 </br> 占比：${params.data.proportion} % </br> 产值：${params.data.contractPrice} 万元</p>`
            return res
          }
        },
        toolbox: {
          show: true
        },
        grid: {
          top: '120px',
          left: '1%',
          bottom: '20px',
          containLabel: true
        },
        legend: {
          left: '5%',
          top: 10,
          show: true,
          orient: 'vertical',
          data: this.legend,
          textStyle: { // 图例文字的样式
            color: '#6AA4F5',
            fontSize: 12
          }
        },
        series: [{
          name: '项目类型',
          type: 'pie',
          radius: [0, 65],
          center: ['55%', '70%'],
          color: color,
          label: {
            position: 'inside',
            formatter: function(param) {
              if (param.value) {
                return param.value
              } else {
                return ''
              }
            },
            fontSize: 12,
            color: '#fff'
          },
          data: newData
        }]
      }
      // 给实例对象添加配置参数
      this.myChart.setOption(options)
      this.myChart.on('click', this.ClickPie)
      window.addEventListener('resize', this.resizeHandler)
    },
    // 点击地貌
    ClickPie(param) {
      this.$emit('setTitle', param.name)
    },
    // 图形根据容器大小来进行缩放
    resizeHandler() {
      this.myChart.resize()
    }
  }
}
</script>

